﻿using System;
using System.Collections.Generic;

namespace GodSharp.Communications.Abstractions
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class CommunicationModuleBase : ICommunicationHandler
    {
        /// <summary>
        /// Gets the entry points.
        /// </summary>
        /// <value>
        /// The entry points.
        /// </value>
        public string[] EntryPoints { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="CommunicationModuleBase"/> class.
        /// </summary>
        public CommunicationModuleBase()
        {
            EntryPoints = GetEntryPoints();
        }
        
        /// <summary>
        /// Gets the entry points.
        /// </summary>
        /// <exception cref="Exception">
        /// Not found entry point in this module.
        /// or
        /// Not found entry point in this module.
        /// </exception>
        private string[] GetEntryPoints()
        {
            object[] attributes = this.GetType().GetCustomAttributes(typeof(EntryPointAttribute), false);

            if (attributes == null || attributes.Length < 1) throw new Exception("Not found entry point in this module.");

            List<string> list = new List<string>();

            foreach (var item in attributes)
            {
                EntryPointAttribute attribute = item as EntryPointAttribute;

                if (attribute == null) continue;

                string point = attribute.EntryPoint?.Trim();

                if (point.IsNullOrWhiteSpace()) continue;

                if (list.Contains(point)) continue;

                list.Add(point);
            }

            if (list.Count < 1) throw new Exception("Not found entry point in this module.");

            return list.ToArray();
        }
    }
}